package com.example.demo.app.controller;

import com.example.demo.app.entity.FormEntity;
import com.example.demo.config.builder.ComplexFormStateMachineBuilder;
import com.example.demo.config.enum_.ComplexFormEvents;
import com.example.demo.config.enum_.ComplexFormStates;
import com.example.demo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
@Slf4j
public class StateMachineController2 {
	@Autowired
	private ComplexFormStateMachineBuilder complexFormStateMachineBuilder;
	@Autowired
	private BeanFactory beanFactory;
	/**
	 * 取一个任何状态节点的状态机，继续往下执行
	 */
	//@Resource(name= PersistConfig.formPersister)
	//private StateMachinePersister<ComplexFormStates, ComplexFormEvents, FormEntity> formPersister;

	//恢复状态机
			// formPersister.restore(stateMachine, form1);
			// 查看恢复后状态机的状态
			// System.out.println("恢复后的状态：" + stateMachine.getState().getId());

	@RequestMapping("/testComplexFormState")
	public void testComplexFormState(String id,String text) throws Exception {
		
		StateMachine<ComplexFormStates, ComplexFormEvents> stateMachine = complexFormStateMachineBuilder.build(beanFactory);
		System.out.println(stateMachine.getId());
		
		FormEntity form1 = new FormEntity(id,text,null);
		

		// 创建流程
		System.out.println("-------------------form1------------------");
		
		stateMachine.start();
		Message message = MessageBuilder.withPayload(ComplexFormEvents.WRITE).setHeader("form", form1).build();
		stateMachine.sendEvent(message);
		System.out.println("当前状态：" + stateMachine.getState().getId());
		
		message = MessageBuilder.withPayload(ComplexFormEvents.CHECK).setHeader("form", RedisUtil.get(form1.getId(),FormEntity.class)).build();
		stateMachine.sendEvent(message);
		System.out.println("当前状态：" + stateMachine.getState().getId());
		
		message = MessageBuilder.withPayload(ComplexFormEvents.DEAL).setHeader("form", RedisUtil.get(form1.getId(),FormEntity.class)).build();
		stateMachine.sendEvent(message);
		System.out.println("当前状态：" + stateMachine.getState().getId());
		
		message = MessageBuilder.withPayload(ComplexFormEvents.SUBMIT).setHeader("form", RedisUtil.get(form1.getId(),FormEntity.class)).build();
		stateMachine.sendEvent(message);
		System.out.println("最终状态：" + stateMachine.getState().getId());
		
		System.out.println("最终状态：" + RedisUtil.get(form1.getId(),FormEntity.class));
	}
}
